package com.renwei.yunlong.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.renwei.yunlong.R;
import com.renwei.yunlong.activity.news.MsgCompanyDetailActivity;
import com.renwei.yunlong.base.BaseFragment;
import com.renwei.yunlong.bean.CommonBean;
import com.renwei.yunlong.bean.MessageCompanyBean;
import com.renwei.yunlong.bean.MessageCompanyOwnerJsonBean;
import com.renwei.yunlong.bean.MessageCompanyServiceJsonBean;
import com.renwei.yunlong.event.MsgCompanyInviEvent;
import com.renwei.yunlong.event.MsgCompanyStateRefreshEvent;
import com.renwei.yunlong.http.HttpPresenter;
import com.renwei.yunlong.http.HttpTaskListener;
import com.renwei.yunlong.utils.JsonMapUtil;
import com.renwei.yunlong.utils.ServiceRequestManager;
import com.renwei.yunlong.view.CircleTextImage;
import com.renwei.yunlong.view.RoundView;
import com.renwei.yunlong.view.SwipeMenuLayout;
import com.zyf.fwms.commonlibrary.base.baseadapter.BaseRecyclerViewAdapter;
import com.renwei.yunlong.http.Api;

import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;

/**
 * Created by wangqi on 2017/10/11.
 */

public class MessageCompanyFragment extends BaseFragment implements HttpTaskListener {
    @Bind(R.id.recyclerView)
    XRecyclerView recyclerView;
    private int page = 1;

    private SwipeAdapter adapter;
    private boolean isSend;

    public MessageCompanyFragment() {
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_message_company;
    }

    @SuppressLint("ValidFragment")
    public MessageCompanyFragment(boolean isSend) {
        this.isSend = isSend;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        ButterKnife.unbind(this);
    }


    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        EventBus.getDefault().register(this);

        adapter = new SwipeAdapter(getContext());
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setAdapter(adapter);
        recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                if (adapter != null) {
                    recyclerView.setLoadingMoreEnabled(false);
                    adapter.clean();
                    page = 1;
                    initData();
                }
            }

            @Override
            public void onLoadMore() {
                page++;
                initData();
            }
        });
        initData();
    }

    public void initData() {
        ServiceRequestManager manager = ServiceRequestManager.getManager();
        String json = "";
        if ("1".equals(companyType)) {
            json = new Gson().toJson(new MessageCompanyOwnerJsonBean(isSend ? 1 : 0
                    , ownerBean.getRows().getOwnerCode(), page, 20));
        } else if ("2".equals(companyType)) {
            json = new Gson().toJson(new MessageCompanyServiceJsonBean(isSend ? 0 : 1, serviceLoginBean.getRows().getServiceProviderCode()
                    , page, 20));
        }
        manager.queryCompanyInviteMsg(getActivity(), json, this);

    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onStateRefresh(MsgCompanyStateRefreshEvent event) {
        recyclerView.refresh();
    }

    /**
     * 刷新
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onRefresh(MsgCompanyInviEvent event) {
        adapter.clean();
        recyclerView.setLoadingMoreEnabled(false);
        page = 1;
        initData();
    }

    @Override
    public void onSuccess(int requestId, String result) {
        switch (requestId) {
            case 666:
                recyclerView.refreshComplete();
                recyclerView.loadMoreComplete();
                MessageCompanyBean bean = new Gson().fromJson(result, MessageCompanyBean.class);
                if (bean.getMessage().getCode() == 200) {
                    if (bean.getRows().size() < 20) {
                        recyclerView.setLoadingMoreEnabled(false);
                    }
                    adapter.addAll(bean.getRows());
                } else {
                    page--;
                    showCenterInfoMsg(bean.getMessage().getMessage());
                }
                break;
            default:
                break;
        }
    }


    @Override
    public void onException(int requestId, String code) {
        page--;
        recyclerView.refreshComplete();
        recyclerView.loadMoreComplete();
    }

    class SwipeAdapter extends BaseRecyclerViewAdapter<MessageCompanyBean.RowsBean> {

        public SwipeAdapter(Context context) {
            super(context);
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new MyViewHolder(LayoutInflater.from(getContext()).inflate(R.layout.item_message_company, null));
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
            final MyViewHolder viewHolder = (MyViewHolder) holder;
            final MessageCompanyBean.RowsBean bean = getItem(position);
            if ("1".equals(bean.getIsRead())) {
                viewHolder.ivBot.setVisibility(View.GONE);
            } else {
                viewHolder.ivBot.setVisibility(View.VISIBLE);
            }

            if ("1".equals(companyType)) {
                viewHolder.tvName.setText(bean.getServerName());
            } else {
                viewHolder.tvName.setText(bean.getOwnerName());
            }

            viewHolder.ivHead.setText4CircleImage(String.valueOf(viewHolder.tvName.getText().toString()));

            viewHolder.tvContent.setText(bean.getRelationDesc());
            String[] ts = bean.getCreateTime().split("T");
            viewHolder.tvTime.setText(ts[0]);
            if ("0".equals(bean.getStatus())) {
                viewHolder.smlayout.setSwipeEnable(isSend);
                viewHolder.tvState.setText("待审核");
                viewHolder.tvState.setBackground(getContext().getResources().getDrawable(R.drawable.shape_card_e64545));
                viewHolder.ivHead.setTextCircleColor(Color.parseColor("#e64545"));
            } else if ("1".equals(bean.getStatus())) {
                viewHolder.smlayout.setSwipeEnable(false);
                viewHolder.tvState.setText("已通过");
                viewHolder.tvState.setBackground(getContext().getResources().getDrawable(R.drawable.shape_card_76c56d));
                viewHolder.ivHead.setTextCircleColor(Color.parseColor("#76c56d"));
            } else if ("2".equals(bean.getStatus())) {
                viewHolder.tvState.setText("已拒绝");
                viewHolder.smlayout.setSwipeEnable(false);
                viewHolder.tvState.setBackground(getContext().getResources().getDrawable(R.drawable.shape_card_b8bfcc));
                viewHolder.ivHead.setTextCircleColor(Color.parseColor("#b8bfcc"));
            } else if ("3".equals(bean.getStatus())) {
                viewHolder.tvState.setText("已解绑");
                viewHolder.smlayout.setSwipeEnable(false);
                viewHolder.tvState.setBackground(getContext().getResources().getDrawable(R.drawable.shape_card_b8bfcc));
                viewHolder.ivHead.setTextCircleColor(Color.parseColor("#b8bfcc"));
            }
            viewHolder.btnZd.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    viewHolder.smlayout.smoothClose();
                    dealBtn(false, bean, position);
                }
            });
            viewHolder.btnDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // 同意
                    viewHolder.smlayout.smoothClose();
                    dealBtn(true, bean, position);
                }
            });
            viewHolder.rlRoot.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!"1".equals(bean.getIsRead())) {
                        bean.setIsRead("1");
                        notifyDataSetChanged();
                    }
                    MsgCompanyDetailActivity.OpenActivity(getContext(), bean.getRelationId(), isSend, position);
                }
            });
        }

    }

    class MyViewHolder extends RecyclerView.ViewHolder {
        @Bind(R.id.iv_head)
        CircleTextImage ivHead;
        @Bind(R.id.iv_bot)
        RoundView ivBot;
        @Bind(R.id.rl_iv)
        RelativeLayout rlIv;
        @Bind(R.id.tv_time)
        TextView tvTime;
        @Bind(R.id.tv_state)
        TextView tvState;
        @Bind(R.id.tv_name)
        TextView tvName;
        @Bind(R.id.tv_content)
        TextView tvContent;
        @Bind(R.id.rl_root)
        RelativeLayout rlRoot;
        @Bind(R.id.btn_zd)
        Button btnZd;
        @Bind(R.id.btn_delete)
        Button btnDelete;
        @Bind(R.id.smlayout)
        SwipeMenuLayout smlayout;

        public MyViewHolder(View view) {
            super(view);
            ButterKnife.bind(this, view);
        }
    }


    private void dealBtn(final boolean b, MessageCompanyBean.RowsBean bean, final int position) {
        HttpPresenter hp = new HttpPresenter(getContext());
        HashMap<String, String> map = new HashMap<>();
        if ("1".equals(companyType)) {
            hp.setUrl(Api.$().OWNER_MESSAGE_COMPANY_DETAIL_DEAL);
            map.put("relationId", bean.getRelationId() + "");
            map.put("status", b ? "1" : "2");
            map.put("ownerCode", ownerBean.getRows().getOwnerCode());
            map.put("currentUserId", ownerBean.getRows().getEmployeeId());
            hp.putParam("jsonBean", JsonMapUtil.mapToJson(map));
        } else if ("2".equals(companyType)) {
            hp.setUrl(Api.$().SERVICE_MESSAGE_COMPANY_DETAIL_DEAL);
            map.put("relationId", bean.getRelationId() + "");
            map.put("status", b ? "1" : "2");
            map.put("serviceProviderCode", serviceLoginBean.getRows().getServiceProviderCode());
            map.put("currentUserId", serviceLoginBean.getRows().getEmployeeId());
            hp.putParam("jsonBean", JsonMapUtil.mapToJson(map));
        }
        hp.setshowDialogcontent("正在加载");
        hp.setCallBack(new HttpTaskListener() {
            @Override
            public void onSuccess(int requestId, String result) {
                CommonBean bean = new Gson().fromJson(result, CommonBean.class);
                if (bean.getMessage().getCode() == 200) {
                    adapter.getItem(position).setStatus(b ? "1" : "2");
                    adapter.notifyDataSetChanged();
                } else {
                    showCenterInfoMsg(bean.getMessage().getMessage());
                }
            }

            @Override
            public void onException(int requestId, String code) {

            }
        });
        hp.post();
    }

}
